-- Last Updated: June 10th, 2009

function QuickSplit_OnLoad(this)
	DEFAULT_CHAT_FRAME:AddMessage("QuickSplit v0.4 loaded")
	this:RegisterEvent("LOADING_END")
end


local function FindEmptyBagSlot()
	local _, totalBagSlots = GetBagCount()
	for i = 1, totalBagSlots do
		local bagIndex, iconFile = GetBagItemInfo(i)
		if not iconFile or iconFile == "" then
			return bagIndex
		end
	end
end


local alreadyHooked = false
local old_BagItemButton_OnClick = nil

function QuickSplit_BagItemButton_OnClick(this, button, ignoreShift)
	if ( IsCtrlKeyDown() and IsShiftKeyDown() ) then
		local emptySlot =	FindEmptyBagSlot()
		local _, _, _, itemCount = GetBagItemInfo(this:GetID())

		if emptySlot and itemCount > 1 then
			SplitBagItem(this.index, 1)
			PickupBagItem(emptySlot) -- put item in empty bag slot
		end
	else
		assert(old_BagItemButton_OnClick ~= nil)
		old_BagItemButton_OnClick(this, button, ignoreShift)
	end
end


local function CreateHook()
	if ( not alreadyHooked ) then
		if (type(yBagItem_OnClick) == "function") then
			old_BagItemButton_OnClick = yBagItem_OnClick
			yBagItem_OnClick = QuickSplit_BagItemButton_OnClick
		else
			old_BagItemButton_OnClick = BagItemButton_OnClick
			BagItemButton_OnClick = QuickSplit_BagItemButton_OnClick
		end
		alreadyHooked = true
	end
end


function QuickSplit_OnEvent(this, event)
	if ( event == "LOADING_END" ) then
		CreateHook()
	end
end



